import random
from database_manager import get_db_connection
from analysis_manager import generate_stock_analysis
from time import sleep


def get_qualified_stocks():
    """
    获取符合条件的股票：60和00开头，排除603开头
    使用已知可以正常工作的股票代码格式
    """
    # 优先使用已知可用的股票列表，使用正确的交易所后缀格式
    qualified_stocks = [
        # 证券行业
        {'symbol': '600030.SS', 'symbol_standardized': '600030', 'stock_name': '中信证券', 'industry': '证券'},
        {'symbol': '000776.SZ', 'symbol_standardized': '000776', 'stock_name': '广发证券', 'industry': '证券'},
        {'symbol': '601688.SS', 'symbol_standardized': '601688', 'stock_name': '华泰证券', 'industry': '证券'},
        {'symbol': '600837.SS', 'symbol_standardized': '600837', 'stock_name': '海通证券', 'industry': '证券'},
        {'symbol': '601377.SS', 'symbol_standardized': '601377', 'stock_name': '兴业证券', 'industry': '证券'},
        
        # 银行行业
        {'symbol': '601288.SS', 'symbol_standardized': '601288', 'stock_name': '农业银行', 'industry': '银行'},
        {'symbol': '601398.SS', 'symbol_standardized': '601398', 'stock_name': '工商银行', 'industry': '银行'},
        {'symbol': '601939.SS', 'symbol_standardized': '601939', 'stock_name': '建设银行', 'industry': '银行'},
        {'symbol': '600036.SS', 'symbol_standardized': '600036', 'stock_name': '招商银行', 'industry': '银行'},
        {'symbol': '000001.SZ', 'symbol_standardized': '000001', 'stock_name': '平安银行', 'industry': '银行'},
        
        # 保险行业
        {'symbol': '601628.SS', 'symbol_standardized': '601628', 'stock_name': '中国人寿', 'industry': '保险'},
        {'symbol': '601318.SS', 'symbol_standardized': '601318', 'stock_name': '中国平安', 'industry': '保险'},
        {'symbol': '601601.SS', 'symbol_standardized': '601601', 'stock_name': '中国太保', 'industry': '保险'},
        {'symbol': '601336.SS', 'symbol_standardized': '601336', 'stock_name': '新华保险', 'industry': '保险'},
        
        # 汽车制造
        {'symbol': '600104.SS', 'symbol_standardized': '600104', 'stock_name': '上汽集团', 'industry': '汽车制造'},
        {'symbol': '000625.SZ', 'symbol_standardized': '000625', 'stock_name': '长安汽车', 'industry': '汽车制造'},
        {'symbol': '601238.SS', 'symbol_standardized': '601238', 'stock_name': '广汽集团', 'industry': '汽车制造'},
        {'symbol': '600418.SS', 'symbol_standardized': '600418', 'stock_name': '江淮汽车', 'industry': '汽车制造'},
        {'symbol': '000800.SZ', 'symbol_standardized': '000800', 'stock_name': '一汽轿车', 'industry': '汽车制造'},
        
        # 医药生物
        {'symbol': '000661.SZ', 'symbol_standardized': '000661', 'stock_name': '长春高新', 'industry': '医药生物'},
        {'symbol': '600518.SS', 'symbol_standardized': '600518', 'stock_name': '康美药业', 'industry': '医药生物'},
        {'symbol': '600276.SS', 'symbol_standardized': '600276', 'stock_name': '恒瑞医药', 'industry': '医药生物'},
        {'symbol': '000538.SZ', 'symbol_standardized': '000538', 'stock_name': '云南白药', 'industry': '医药生物'},
        {'symbol': '600867.SS', 'symbol_standardized': '600867', 'stock_name': '通化东宝', 'industry': '医药生物'},
        
        # 电子行业
        {'symbol': '000413.SZ', 'symbol_standardized': '000413', 'stock_name': '东旭光电', 'industry': '电子'},
        {'symbol': '002475.SZ', 'symbol_standardized': '002475', 'stock_name': '立讯精密', 'industry': '电子'},
        {'symbol': '002049.SZ', 'symbol_standardized': '002049', 'stock_name': '紫光国微', 'industry': '电子'},
        {'symbol': '002185.SZ', 'symbol_standardized': '002185', 'stock_name': '华天科技', 'industry': '电子'},
        {'symbol': '000021.SZ', 'symbol_standardized': '000021', 'stock_name': '深科技', 'industry': '电子'},
        
        # 计算机行业
        {'symbol': '000938.SZ', 'symbol_standardized': '000938', 'stock_name': '紫光股份', 'industry': '计算机'},
        {'symbol': '002195.SZ', 'symbol_standardized': '002195', 'stock_name': '二三四五', 'industry': '计算机'},
        {'symbol': '600588.SS', 'symbol_standardized': '600588', 'stock_name': '用友网络', 'industry': '计算机'},
        {'symbol': '600756.SS', 'symbol_standardized': '600756', 'stock_name': '浪潮软件', 'industry': '计算机'},
        {'symbol': '002268.SZ', 'symbol_standardized': '002268', 'stock_name': '卫士通', 'industry': '计算机'},
        
        # 通信设备
        {'symbol': '000063.SZ', 'symbol_standardized': '000063', 'stock_name': '中兴通讯', 'industry': '通信设备'},
        {'symbol': '600498.SS', 'symbol_standardized': '600498', 'stock_name': '烽火通信', 'industry': '通信设备'},
        {'symbol': '002465.SZ', 'symbol_standardized': '002465', 'stock_name': '海格通信', 'industry': '通信设备'},
        {'symbol': '002547.SZ', 'symbol_standardized': '002547', 'stock_name': '春兴精工', 'industry': '通信设备'},
        
        # 能源行业
        {'symbol': '600900.SS', 'symbol_standardized': '600900', 'stock_name': '长江电力', 'industry': '电力'},
        {'symbol': '601857.SS', 'symbol_standardized': '601857', 'stock_name': '中国石油', 'industry': '石油石化'},
        {'symbol': '000983.SZ', 'symbol_standardized': '000983', 'stock_name': '西山煤电', 'industry': '煤炭开采'},
        {'symbol': '600028.SS', 'symbol_standardized': '600028', 'stock_name': '中国石化', 'industry': '石油石化'},
        {'symbol': '600395.SS', 'symbol_standardized': '600395', 'stock_name': '盘江股份', 'industry': '煤炭开采'},
        {'symbol': '600795.SS', 'symbol_standardized': '600795', 'stock_name': '国电电力', 'industry': '电力'},
        
        # 有色金属
        {'symbol': '601899.SS', 'symbol_standardized': '601899', 'stock_name': '紫金矿业', 'industry': '有色金属'},
        {'symbol': '600362.SS', 'symbol_standardized': '600362', 'stock_name': '江西铜业', 'industry': '有色金属'},
        {'symbol': '000878.SZ', 'symbol_standardized': '000878', 'stock_name': '云南铜业', 'industry': '有色金属'},
        {'symbol': '002128.SZ', 'symbol_standardized': '002128', 'stock_name': '露天煤业', 'industry': '有色金属'},
        {'symbol': '601600.SS', 'symbol_standardized': '601600', 'stock_name': '中国铝业', 'industry': '有色金属'},
        
        # 消费品
        {'symbol': '600887.SS', 'symbol_standardized': '600887', 'stock_name': '伊利股份', 'industry': '乳制品'},
        {'symbol': '600519.SS', 'symbol_standardized': '600519', 'stock_name': '贵州茅台', 'industry': '白酒'},
        {'symbol': '000858.SZ', 'symbol_standardized': '000858', 'stock_name': '五粮液', 'industry': '白酒'},
        {'symbol': '000423.SZ', 'symbol_standardized': '000423', 'stock_name': '东阿阿胶', 'industry': '医药生物'},
        {'symbol': '000895.SZ', 'symbol_standardized': '000895', 'stock_name': '双汇发展', 'industry': '食品加工'},
        
        # 房地产
        {'symbol': '600048.SS', 'symbol_standardized': '600048', 'stock_name': '保利发展', 'industry': '房地产'},
        {'symbol': '000002.SZ', 'symbol_standardized': '000002', 'stock_name': '万科A', 'industry': '房地产'},
        {'symbol': '600383.SS', 'symbol_standardized': '600383', 'stock_name': '金地集团', 'industry': '房地产'},
        {'symbol': '000656.SZ', 'symbol_standardized': '000656', 'stock_name': '金科股份', 'industry': '房地产'},
        
        # 物流
        {'symbol': '002352.SZ', 'symbol_standardized': '002352', 'stock_name': '顺丰控股', 'industry': '物流'},
        {'symbol': '600029.SS', 'symbol_standardized': '600029', 'stock_name': '南方航空', 'industry': '航空运输'},
        {'symbol': '601111.SS', 'symbol_standardized': '601111', 'stock_name': '中国国航', 'industry': '航空运输'},
        {'symbol': '000039.SZ', 'symbol_standardized': '000039', 'stock_name': '中集集团', 'industry': '物流'},
        
        # 半导体
        {'symbol': '600703.SS', 'symbol_standardized': '600703', 'stock_name': '三安光电', 'industry': '半导体'},
        {'symbol': '002079.SZ', 'symbol_standardized': '002079', 'stock_name': '苏州固锝', 'industry': '半导体'},
        {'symbol': '002156.SZ', 'symbol_standardized': '002156', 'stock_name': '通富微电', 'industry': '半导体'},
        {'symbol': '600584.SS', 'symbol_standardized': '600584', 'stock_name': '长电科技', 'industry': '半导体'}
    ]
    
    print(f"使用预定义的符合条件的股票列表，共{len(qualified_stocks)}个股票")
    
    return qualified_stocks


def batch_analyze_stocks(sample_size=60):
    """
    批量分析股票并保存到数据库
    """
    print(f"开始批量分析股票，将从符合条件的股票中随机选择{sample_size}个进行分析")
    
    # 获取符合条件的股票
    qualified_stocks = get_qualified_stocks()
    print(f"找到{len(qualified_stocks)}个符合条件的股票")
    
    # 随机选择sample_size个股票
    if len(qualified_stocks) > sample_size:
        selected_stocks = random.sample(qualified_stocks, sample_size)
    else:
        selected_stocks = qualified_stocks
        print(f"符合条件的股票数量不足{sample_size}个，将分析所有{len(selected_stocks)}个股票")
    
    # 分析每个股票
    success_count = 0
    fail_count = 0
    
    print(f"开始分析{len(selected_stocks)}个股票...")
    
    for index, stock in enumerate(selected_stocks, 1):
        symbol = stock['symbol']
        stock_name = stock['stock_name']
        print(f"\n[{index}/{len(selected_stocks)}] 开始分析股票: {symbol} {stock_name}")
        
        try:
            # 调用分析函数（这个函数会自动将结果保存到数据库）
            result = generate_stock_analysis(symbol)
            
            if 'error' in result:
                print(f"分析失败: {result['error']}")
                fail_count += 1
            else:
                print(f"分析成功: {symbol} {stock_name}")
                success_count += 1
                # 检查是否是从缓存获取的
                if result.get('from_cache'):
                    print(f"(从缓存获取)")
                else:
                    print(f"(已保存到数据库)")
            
            # 分析间隔，避免API调用过于频繁
            if index < len(selected_stocks):
                print("等待5秒后进行下一个分析...")
                sleep(5)
                
        except Exception as e:
            print(f"分析过程中出错: {e}")
            fail_count += 1
    
    # 打印统计信息
    print(f"\n批量分析完成！")
    print(f"成功: {success_count} 个")
    print(f"失败: {fail_count} 个")
    
    return success_count, fail_count


if __name__ == "__main__":
    print("==== 股票批量分析工具 ====")
    print("将分析60和00开头（排除603开头）的股票")
    print("======================")
    
    success, fail = batch_analyze_stocks(sample_size=60)
    
    if success > 0:
        print(f"\n已成功分析并保存{success}个股票的分析结果到数据库！")
    else:
        print("\n分析过程中没有成功保存任何结果，请检查日志获取详细信息。")
